package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.common.result.R;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {

    @Autowired
    UserAccountService userAccountService;

    @Autowired
    TransFlowService transFlowService;

    @PostMapping("commitCharge")
    public R commitCharge(String chargeAmt, HttpServletRequest request){
        String userId = request.getHeader("userId");
        String form = userAccountService.commitCharge(userId,chargeAmt);
        return R.ok().data("form",form);
    }

    @PostMapping("/notify")
    public String notifyCommitCharge(HttpServletRequest request){
        Map<String, Object> stringObjectMap = RequestHelper.switchMap(request.getParameterMap());
        String chargeNo = (String)stringObjectMap.get("agentBillNo");
        //订单号存在返回true，不存在返回false
        boolean b = transFlowService.isTranExist(chargeNo);
        //如果不为真，则抛出异常
//        Assert.isTrue(!b, ResponseEnum.COMMON_ERROR);
        if(b){
            return "success";
        }
        userAccountService.notifyCommitCharge(stringObjectMap);
        return "success";
    }

    @GetMapping("/getUserAccountByUserId")
    public R getUserAccountByUserId(HttpServletRequest request){
        String userId = request.getHeader("userId");
        BigDecimal account = userAccountService.getUserAccountByUserId(userId);
        return R.ok().data("account",account);
    }

    @GetMapping("/getUserAccountById")
    public R getUserAccountById(HttpServletRequest request){
        String userId = request.getHeader("userId");
        UserAccount account = userAccountService.getUserAccountById(userId);
        return R.ok().data("account",account);
    }

}

